require 'valid_email/email_validator'

class User < ActiveRecord::Base
  include ActiveModel::Validations
  
  validates :username, :uniqueness => true, :presence => true
  validates :email, :presence => true, :email => true
  validates :password_salt, :presence => true
  validates :password_hash, :presence => true

  #Relationships
  has_many :devices
  has_many :items
  belongs_to :company
  belongs_to :jobsite
  
  def self.authenticate(username, password)
    user=find(:first, :conditions => ["username = ?",username])
    #user = find_by_username(username)s
    if user && user.password_hash == Digest::SHA1.hexdigest(password + user.password_salt)  
      #BCrypt::Engine.hash_secret(password, user.password_salt)
      user
    else
      nil
    end
  end
  
  def encrypt_password
    self.password_salt = BCrypt::Engine.generate_salt
    self.password_hash = BCrypt::Engine.hash_secret(self.password, self.password_salt)
  end
end
